package com.dongdongshop.controller;

import com.dongdongshop.config.DongDongSearchConfig;
import com.dongdongshop.data.PageBean;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.item.TbItem;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("search")
public class SearchController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping("searchShow")
    public String searchShow(String content, Model model){
        model.addAttribute("content",content);
        return "search";
    }

    @RequestMapping("listItemByEs")
    @ResponseBody
    public Result listItemByEs(String content,Integer page){
        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setRows(10);
        // 创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("shopindex");
        //指定DSL检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //检索条件,所有的根操作都可以在这里使用
        searchSourceBuilder.from(page*10);
        searchSourceBuilder.size(10);
        searchSourceBuilder.query(QueryBuilders.matchQuery("title",content));
        HighlightBuilder highlight = new HighlightBuilder();
        highlight.field("title");
        highlight.preTags("<span style='color:red'>").postTags("</span>");
        searchSourceBuilder.highlighter(highlight);
        System.out.println(">>>检索条件 : "+searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);
        //执行检索
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, DongDongSearchConfig.COMMON_OPTIONS);
            //分析结果
            System.out.println(">>>返回结果"+search.toString());
            SearchHits hits = search.getHits();
            Long totalHits = hits.getTotalHits();
            Integer totalCount = totalHits.intValue();
            pageBean.setTotalCount(totalCount);
            pageBean.setTotalPage(totalCount%10==0?totalCount/10:(totalCount/10)+1);
            SearchHit[] innerHis = hits.getHits();
            List<TbItem> itemList = new ArrayList<>();
            for (SearchHit hit : innerHis) {
                String sourceAsStringOfUser = hit.getSourceAsString();
                ObjectMapper objectMapper = new ObjectMapper();
                TbItem tbUser = objectMapper.readValue(sourceAsStringOfUser, TbItem.class);
                Map<String, HighlightField> result = hit.getHighlightFields();
                HighlightField titleField  = result.get("title");
                Text[] fragments = titleField.fragments();
                String title="";
                for (Text fragment : fragments) {
                    title+=fragment;
                }
                tbUser.setTitle(title);
                System.out.println("转换后的 User为:"+tbUser);
                itemList.add(tbUser);
            }
            pageBean.setList(itemList);
            return Result.ok().setData(pageBean);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail();
        }

    }
}
